#Metabolic Comparison Analysis


# Load Libraries ----------------------------------------------------------
library(readxl)
library(tidyverse)


# Load Data ---------------------------------------------------------------

##SMR and RMR Data
LabA = read.csv("Data/SMR_A.csv")
LabB = read.csv("Data/SMR_B.csv")
LabC = read.csv("Data/SMR_C.csv")
LabD = read.csv("Data/SMR_D.csv")
LabE = read.csv("Data/SMR_E.csv")
LabF = read.csv("Data/SMR_F.csv")
LabG = read.csv("Data/SMR_G.csv")
LabH = read.csv("Data/SMR_H.csv")
LabI = read.csv("Data/SMR_I.csv")

#Field Data
Field <- read_csv("Data/Field Data.csv")

#Merge
Data = rbind(LabA, LabB, LabC,LabD, LabE,LabF,LabG,LabH,LabI)
Data = merge(Data, Field, by=c("ID","Day","SP","FL"))


#MMR
MMR_A =  read_csv("Data/MMR_A.csv")
MMR_B =  read_csv("Data/MMR_B.csv")
MMR_C =  read_csv("Data/MMR_C.csv")
MMR_D =  read_csv("Data/MMR_D.csv")
MMR_E =  read_csv("Data/MMR_E.csv")
MMR_F =  read_csv("Data/MMR_F.csv")
MMR_G =  read_csv("Data/MMR_G.csv")
MMR_H =  read_csv("Data/MMR_H.csv")
MMR_I =  read_csv("Data/MMR_I.csv")


MMR = rbind(MMR_A, MMR_B,MMR_C,MMR_D,MMR_E,MMR_F,MMR_G,MMR_H,MMR_I)
colnames(MMR)=c("num","ID","MMR")
#Merge
Data=merge(Data,MMR[,c(2,3)],by=c("ID"),all.x=TRUE)
Data=subset(Data, ID !="c13")



# Theme -------------------------------------------------------------------

Theme = theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank(),axis.title=element_text(size=20),axis.text=element_text(size=18))



# Mass Correct ------------------------------------------------------------

#Set all as /g
Data$MR = -Data$MR/Data$Weight
Data$MMR = Data$MMR/Data$Weight
Data$SMR = -Data$SMR
Data$RMR = -Data$RMR
#Create Weight unadjusted
Data$MR2 = Data$MR*Data$Weight
Data$MMR2 = Data$MMR*Data$Weight
Data$SMR2 = Data$SMR*Data$Weight
Data$RMR2=Data$RMR*Data$Weight

#####Compare Correlation and Rank Order


###Mass Correct
#Mass correct as before metabolic rate to body size adjusted by the exponent of the regression 
ggplot(Data, aes(x=log(Weight), y=log(MR2),color=SP))+geom_point()+geom_smooth(method="lm")
ggplot(Data, aes(x=log(Weight), y=log(SMR2),color=SP))+geom_point()+geom_smooth(method="lm")
ggplot(Data, aes(x=log(Weight), y=log(RMR2),color=SP))+geom_point()+geom_smooth(method="lm")
ggplot(Data, aes(x=log(Weight), y=log(MMR2),color=SP))+geom_point()+geom_smooth(method="lm")


m1=lm(log(SMR2)~log(Weight)+SP, Data)
m2=lm(log(RMR2)~log(Weight)+SP, Data)
m3=lm(log(MR2)~log(Weight), Data)
library(lme4)
m4=lm(log(MMR2)~log(Weight)+SP, Data)
summary(m3)
print(m3)

summary(m1)

b1 =coef(m1)[2]
b2 =coef(m2)[2]
b3 =coef(m3)[2]
b4 =coef(m4)[2]

#b=0.65
Data$SMR3 = Data$SMR2/Data$Weight^b1
Data$MR3 = Data$MR2/Data$Weight^b3
Data$RMR3 = Data$RMR2/Data$Weight^b2
Data$MMR3 = Data$MMR2/Data$Weight^b4



# Visualise Lab vs Field --------------------------------------------------

#SMR vs Field RMR
p1 = ggplot(Data,aes(y=log(SMR3), x=log(MR3),color=SP))+geom_point(size=2,alpha=0.5)+geom_smooth(method="lm",size=2)+theme_bw()+Theme+
  theme(legend.position = "none")+ylab(expression(paste("logSMR (mg O"[2]," g"^-"b"," h"^-1,")")))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())+scale_color_manual(values = c("#40B0A6", "#CC6677", "#E1BE6A", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"))

#RMRvs Field RMR
p2 = ggplot(Data,aes(y=log(RMR3), x=log(MR3),color=SP))+geom_point(size=2,alpha=0.5)+geom_smooth(method="lm",size=2)+theme_bw()+Theme+
  theme(legend.position = "none")+ylab(expression(paste("log", RMR[L], " (mg O"[2]," g"^-"b"," h"^-1,")")))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())+scale_color_manual(values =  c("#40B0A6", "#CC6677", "#E1BE6A", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"))#+xlab(expression(paste("logFMR (mgO"^2,"g"^-1,"h"^-1,")")))

#MMR vs Field RMR
p3 = ggplot(Data,aes(y=log(MMR3), x=log(MR3)))+geom_point(aes(color=SP),size=2,alpha=0.5)+theme_bw()+Theme+
  theme(legend.position = "none")+xlab(expression(paste("log", RMR[F], " (mg O"[2]," g"^-"b"," h"^-1,")")))+ylab(expression(paste("logMMR (mgO"[2]," g"^-"b"," h"^-1,")")))+scale_color_manual(values =c("#40B0A6", "#CC6677", "#E1BE6A", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"))


library(cowplot)
p = plot_grid(p1,p2,p3, ncol = 1,align = "v", labels = c("a","b","c"))

plot_grid(p1,p2, ncol = 1,align = "v", labels = c("a","b"))
ggsave("Plots/Lab vs Field MA.tiff", plot = p, width = 6, height = 13, units = "in", dpi = 300)



# Model lab vs field ------------------------------------------------------

#SMR
m1=lm(log(SMR3)~log(MR3)+SP, Data)
m2=lm(log(SMR3)~log(MR3)*SP, Data)
summary(m1)
anova(m1)
AIC(m1,m2)

#RMR
m1=lm(log(RMR3)~log(MR3)+SP, Data)
m2=lm(log(RMR3)~log(MR3)*SP, Data)
m3=lm(log(RMR3)~log(MR3), Data)
summary(m1)
anova(m1)
AIC(m1,m2,m3)

#MMR
m1=lm(log(MMR3)~log(MR3)+SP, Data)
m2=lm(log(MMR3)~log(MR3)*SP, Data)
m3=lm(log(MMR3)~log(MR3), Data)
summary(m3)
anova(m3)
AIC(m1,m2,m3)

m1=lm(SMR~MMR*SP, Data)
m1=lm(SMR3~MMR3*SP, Data)
summary(m1)

#Spearmans Ranks
Trout=subset(Data, SP =="Trout")
Trout=subset(Data, SP =="Stickleback")
Trout=subset(Data, SP =="Minnow")
Trout=subset(Data, SP != "Stickleback")

SP=Trout
SP=Data
spearman_correlation <- cor.test(SP$SMR3,SP$MR3, method = "spearman")
spearman_correlation <- cor.test(SP$SMR,SP$MR, method = "spearman")

spearman_correlation <- cor.test(SP$MR3,SP$RMR3, method = "spearman")
spearman_correlation <- cor.test(SP$MR,SP$RMR, method = "spearman")

spearman_correlation <- cor.test(SP$MR3,SP$MMR3, method = "spearman")
spearman_correlation <- cor.test(SP$MR,SP$MMR, method = "spearman")

print(spearman_correlation)
spearman_correlation <- cor.test(SP$SMR3,SP$MR4, method = "kendall")





# Compare differences -----------------------------------------------------

#prep Data
Long =  dplyr::select(Data, ID,Day,SP, SMR,RMR,MR,MMR,Weight)
Long =  dplyr::select(Data, ID,Day,SP, SMR3,RMR3,MR3,MMR3,Weight)
library(data.table)
long <- melt(setDT(Long), id.vars = c("ID","SP","Day","Weight"), variable.name = "Method")

#Relabel
long$Method <- factor(long$Method, levels = c("SMR3", "RMR3", "MR3", "MMR3"),
                      labels = c("SMR", "RMR^L", "RMR^F", "MMR"))
#V2
po = ggplot(long, aes(x=Method, y=log(value)))+geom_boxplot(outliers=FALSE)+geom_jitter(width = 0.05, size = 1.5, alpha = 0.7)+
  facet_wrap(~SP)+theme_bw()+Theme+theme(legend.position = 0, 
                                         strip.text = element_text(size = 18))+ylab(expression(paste("log Metabolic Rate (mg O"[2]," g"^-"b"," h"^-1,")")))+ scale_x_discrete(
    labels = c(
      "SMR" = "SMR",
      "RMR^L" = bquote(RMR[L]),
      "RMR^F" = bquote(RMR[F]),
      "MMR" = "MMR"
    ))
ggsave("Plots/Metabolism Offsets MA.tiff", plot = po, width = 10, height = 6, units = "in", dpi = 300)

#ANother version
ggplot(long, aes(x=Method, y=log(value)))+
  geom_line(aes(group=ID),alpha=0.5)+geom_boxplot(outliers=FALSE,alpha=0.3)+geom_jitter(width = 0.05, size = 1.5, alpha = 0.7)+
  facet_wrap(~SP)+theme_bw()+Theme+theme(legend.position = 0, 
                                         strip.text = element_text(size = 18))+ylab(expression(paste("log Metabolic Rate (mgO"^2,"h"^-1,")")))+ scale_x_discrete(
                                           labels = c(
                                             "SMR" = "SMR",
                                             "RMR^L" = bquote(RMR[L]),
                                             "RMR^F" = bquote(RMR[F]),
                                             "MMR" = "MMR"
                                           ))


#Model
library(lme4)
library(lmerTest)
library(MASS)
library(nlme)
long=na.omit(long)
#m1 = lm((value)~Method*SP+Weight, long)
m1 = glmer(log(value)~Method*SP+(1 |ID), data=long)#Variance increases with MMR how do we best account for this in the model
#m1 = glmer(log(value)~Method*SP+Weight+(1 |ID), data=long)

#m2 <- gls(log(value) ~ Method * SP + Weight, data = long, weights = varIdent(form = ~ 1 | Method))

m2 = gls(log(value) ~ Method * SP , data = long, weights = varIdent(form = ~ 1 | Method))

#m1 <- lme(fixed = log(value) ~ Method * SP + Weight,random = list(ID = pdDiag(~ Method)),data = long,
#          weights = varIdent(form = ~ 1 | Method))

m1<- lme(fixed = log(value) ~ factor(Method) * SP ,random = ~1|ID,data = long,
         weights = varIdent(form = ~ 1 | Method))
m2<- lme(fixed = log(value) ~ Method * SP ,random = ~1|ID,data = long,
         weights = varExp(form = ~ fitted(.)))
m3 = gls(log(value) ~ Method * SP , data = long, weights = varIdent(form = ~ 1 | Method))
m4 = glmer(log(value)~Method*SP+(1 |ID), data=long)

install.packages("performance")
library(performance)
r2(m1)

AIC(m1,m2,m3,m4)
anova(m1)
summary(m1)
plot(m1, resid(.) ~ fitted(.), id = 0.05)

citation("rptR")
#Check
E1 = resid(m1, type ="pearson")
F1=fitted(m1)
eta=predict(m1, type="link")
plot(x=F1,y=E1)
abline(h=0,v=0,lty=2)
plot(x=eta,y=E1)
plot(x=log(long$value),y=E1)
boxplot(E1~long$Method)
acf(resid(m1), main = "ACF of Residuals")
qqnorm(residuals(m1))
qqline(residuals(m1))
ranef(m1)
library(car)
vif(m1)

mean(Data$SMR)


## More detail -------------------------------------------------------------


#Look at differences
mod = summary(m1)
mod$coefficients
(mod$coefficients[3])/mean(Data$SMR)#MR vs SMR
(mod$coefficients[1]+mod$coefficients[3])/mod$coefficients[4]#MR vs MMR
(mod$coefficients[4]+mod$coefficients[1])/mod$coefficients[1]#SMR vs MMR
(mod$coefficients[1]+mod$coefficients[4]+mod$coefficients[13])/mod$coefficients[1]#SMR vs MMR Trout
library(emmeans)
# Estimated marginal means with post hoc pairwise comparisons
emmeans_results <- emmeans(m1, ~ Method|SP)
summary(emmeans_results)
# Pairwise comparisons within each species
pairwise_comparisons <- pairs(emmeans_results, adjust = "bonferroni")
pairwise_comparisons

##PredictedDifferences
library(dplyr)
predicted_values <- predict(m1)
predicted_values <- predict(m1,levels=0)
fitted=fitted(m1)
results <- data.frame(
  Observed = long$value,
  Predicted = predicted_values,
  Method = long$Method,
  SP = long$SP
)

results <- results %>%
  mutate(Predicted_Original = exp(Predicted))

mean_predicted <- results %>%
  group_by(Method, SP) %>%
  summarize(MeanPredicted = mean(Predicted_Original))

#Predict onto new data
new_data <- expand.grid(
  Method = unique(long$Method),
  SP = c("Minnow", "Stickleback","Trout"),
  ID = unique(long$ID)  # Placeholder for random effect grouping variable (if not needed)
)

# Add any continuous predictors, covering their range
new_data$value <- seq(min(log(long$value)), max(log(long$value)), length.out = nrow(new_data))


new_data$Predicted <- predict(m1, newdata = new_data)#Can add level = 0 to remove random effects

new_data$Predicted_Original <- exp(new_data$Predicted)

new_data%>%
  group_by(Method, SP)%>%
  summarise(mean(Predicted_Original))

#Scope for minnows = 1.56-0.252, trout = 0.827-0.115, absolute means, 1.31 vs 0.712 but factorial means 6.19  vs 7.2
#plot
Data$AS_abs=Data$MMR-Data$SMR
Data$AS_fct=Data$MMR/Data$SMR
Data$FMR_fct=Data$MR3/Data$SMR3
length(Data$FMR_fct)
1-11/53

ggplot(Data, aes(x=SMR ,y=AS_abs,color=SP))+geom_point()+geom_smooth(method="lm")
ggplot(Data, aes(x=SMR, y=AS_fct,color=SP))+geom_point()+geom_smooth(method="lm")
m1 = lm(AS_abs~MR3*SP, Data)
anova(m1)

#Can use emeans too
library(emmeans)
emm <- emmeans(m1, ~ Method)
emm_original <- emmeans(m1, ~ Method, type = "response")
summary(emm_original)
pairs(emm_original)
emm_original <- emmeans(m1, ~ SP, type = "response")
summary(emm_original)
emm_interaction_original <- emmeans(m1, ~ Method | SP, type = "response")

# Pairwise comparisons within each SP level
pairs(emm_interaction_original)
plot(emm_original)
0.147/0.561

1/0.429
0.305
1/0.131
1/0.2613
1/0.5874
0.2928
1/0.563


1/0.621
# Plot Predictions
library(ggplot2)
ggplot(new_data, aes(y=Predicted_Original,x=Method)) +
  geom_boxplot() +
  theme_minimal()+facet_wrap(~SP)


# Supplimentary Plots -----------------------------------------------------


##MMR vs SMR
m1=lm(log(MMR3)~log(MR3), Data)
m2=lm(log(MMR3)~log(SMR3), Data)
m3=lm(log(MMR3)~log(RMR3), Data)
summary(m1)
summary(m2)
summary(m3)
ggplot(Data,aes(y=log(MR3), x=log(MMR3)))+geom_point(size=2,alpha=0.5)+geom_smooth(method="lm",size=2)+theme_bw()+Theme+
  theme(legend.position = "none")+ylab(expression(paste("logSMR (mgO"^2,"h"^-1,")")))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())+scale_color_manual(values = c("#40B0A6", "#CC6677", "#E1BE6A", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"))



#Plot S1
p1 = ggplot(Data,aes(y=log(SMR3), x=log(MMR3)))+geom_point(aes(color=SP),size=2,alpha=0.7)+geom_smooth(method="lm",size=2)+theme_bw()+Theme+
  theme(legend.position = "none")+ylab(expression(paste("logSMR (mgO"^2,"h"^-1,")")))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())+scale_color_manual(values = c("#40B0A6", "#CC6677", "#E1BE6A", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"))


#RMRvs Field RMR
p2 = ggplot(Data,aes(y=log(RMR3), x=log(MMR3)))+geom_point(aes(color=SP),size=2,alpha=0.7)+geom_smooth(method="lm",size=2)+theme_bw()+Theme+
  theme(legend.position = "none")+ylab(expression(paste("log", RMR[L], " (mgO"^2,"h"^-1,")")))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())+scale_color_manual(values =  c("#40B0A6", "#CC6677", "#E1BE6A", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"))#+xlab(expression(paste("logFMR (mgO"^2,"g"^-1,"h"^-1,")")))

#MMR vs Field RMR
p3 = ggplot(Data,aes(y=log(MR3), x=log(MMR3)))+geom_point(aes(color=SP),size=2,alpha=0.7)+theme_bw()+Theme+
  theme(legend.position = "none")+ylab(expression(paste("log", RMR[F], " (mgO"^2,"h"^-1,")")))+xlab(expression(paste("logMMR (mgO"^2,"h"^-1,")")))+scale_color_manual(values =c("#40B0A6", "#CC6677", "#E1BE6A", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"))
library(cowplot)
p = plot_grid(p1,p2,p3, ncol = 1,align = "v", labels = c("a","b","c"))
ggsave("Plots/S1 MMR.tiff", plot = p, width = 6, height = 11, units = "in", dpi = 300)



p1 = ggplot(Data,aes(y=log(SMR3), x=log(MMR3),color=SP))+geom_point(size=2,alpha=0.7)+geom_smooth(method="lm",size=2)+theme_bw()+Theme+
  theme(legend.position = "none")+ylab(expression(paste("logSMR (mgO"^2,"h"^-1,")")))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())+scale_color_manual(values = c("#40B0A6", "#CC6677", "#E1BE6A", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"))

p2 = ggplot(Data,aes(y=log(MR3), x=log(MMR3),color=SP))+geom_point(size=2,alpha=0.5)+geom_smooth(method="lm",size=2)+theme_bw()+Theme+
  labs(color="Species")+ylab(expression(paste("logSMR (mgO"^2,"h"^-1,")")))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())+scale_color_manual(values = c("#40B0A6", "#CC6677", "#E1BE6A", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"))








#Plot
#SMR vs Field RMR
p1 = ggplot(Data,aes(y=(SMR3), x=(MR3),color=SP))+geom_point()+geom_smooth(method="lm")+theme_bw()+Theme+
  theme(legend.position = 0)+ylab(expression(paste("SMR (mgO"^2,"g"^-1,"h"^-1,")")))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

#RMRvs Field RMR
p2 = ggplot(Data,aes(y=RMR3, x=MR3,color=SP))+geom_point()+geom_smooth(method="lm")+theme_bw()+Theme+
  theme(legend.position = 0)+ylab(expression(paste("RMR (mgO"^2,"g"^-1,"h"^-1,")")))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

#MMR vs Field RMR
p3 = ggplot(Data,aes(y=MMR3, x=MR3))+geom_point(aes(color=SP))+theme_bw()+Theme+
  theme(legend.position = 0)+xlab(expression(paste("FMR (mgO"^2,"g"^-1,"h"^-1,")")))+ylab(expression(paste("MMR (mgO"^2,"g"^-1,"h"^-1,")")))
library(cowplot)
plot_grid(p1,p2,p3, ncol = 1,align = "v", labels = c("a","b","c"))


#Supplimentary Table S1 stats
mean(Data$MinOx_SMR)

DataT=subset(Data, SP=="Trout")
DataT=subset(Data, SP=="Minnow")
DataT=subset(Data, SP=="Stickleback")
mean(abs(Data$Background.as...SMR))


1-mean(Data$R2prop)
1-mean(na.omit(Data)$R2prop)











# CUT FROM HERE -----------------------------------------------------------







###Pres###R2propPres
p1 = ggplot(Data,aes(y=log(SMR3), x=log(MR3),color=SP))+geom_point(size=2)+geom_smooth(method="lm",size=2)+theme_bw()+Theme+
  theme(legend.position = "none")+ylab(expression(paste("BMR")))+
  theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank())

p2 = ggplot(Data,aes(y=log(RMR3), x=log(MR3),color=SP))+geom_point(size=2)+geom_smooth(method="lm",size=2)+theme_bw()+Theme+
  theme(legend.position = "none")+ylab("RMR")+xlab("FMR")


plot_grid(p1,p2, ncol = 1,align = "v", labels = c("a","b"))



ggplot(long, aes(x=Method, y=log(value),fill=SP))+geom_boxplot(outliers = FALSE)+geom_jitter(width = 0.05, size = 1.5, alpha = 0.7)+
  facet_wrap(~SP)+theme_bw()+Theme+theme(legend.position = "none")+ylab(expression(paste("Metabolic Rate")))+scale_x_discrete(labels=c("BMR","RMR","FMR","MMR"))






# Oto Met -----------------------------------------------------------------

#Load and prep Data
Oto <- read_excel("Data/Oto Metabolism p1.xlsx", 
                  sheet = "Data summary")
str(Oto)
Oto=Oto%>%
  dplyr::select(ID,`Normalised δ18O ‰VPDB Mean`,`Normalised δ13C ‰VPDB Mean`)
Oto=na.omit(Oto)

Oto = subset(Oto, `Normalised δ13C ‰VPDB Mean`>-14)#remove outlier
Oto = merge(Data,Oto, by=c("ID"))
Oto = subset(Oto, SP=="Trout")#remove stickles that have juv signal
#Add DIC
Oto$DIC = -7#guess
mean(c(-13.35,-14.24,-10.70,-11.78))
Oto$DIC = -12.5#mean
Oto$DIC = -10.7#mean of last 2 (no air)

mean(Oto$`Normalised δ13C ‰VPDB Mean`)
#Spearmans Rank Correlation
cor.test(Oto$`Normalised δ13C ‰VPDB Mean`,Oto$MR3, method = "spearman")
m1=lm(`Normalised δ13C ‰VPDB Mean`~MR3, data=Oto)
summary(m1)
ggplot(Oto, aes(x=`Normalised δ13C ‰VPDB Mean`,y=MR3))+geom_point()+geom_smooth(method="lm")
ggplot(Oto, aes(x=ID,y=MR3))+geom_point()+geom_smooth(method="lm")+geom_point(aes(y=(`Normalised δ13C ‰VPDB Mean`)+13),color="red")

ggplot(Oto, aes(x=Cresp))+geom_histogram()+facet_wrap(~SP)

#Add diet
Oto=mutate(Oto, Muscle = ifelse(SP=="Trout", -16,NA))
#Oto=mutate(Oto, Muscle = ifelse(SP=="Stickleback", -26,Muscle))#native water more positive than trout, core of stickle oto formed in relativly positive d13C water, this makes lower c resp in those with higher proportion explaining positive rtend in cresp

#Calculate Cresp
Oto=mutate(Oto, Cresp=(`Normalised δ13C ‰VPDB Mean`-DIC)/(Muscle-DIC))

#Calculate FMR
Oto=mutate(Oto, FMR = (Cresp-0.0401)/0.000971)
#Convert to g from kg
Oto$FMR=Oto$FMR/1000

#total range of RMR and what should that translate to in Cresp in constantw ater, how much greater is variance we see than maximum expected difference 
Oto2%>%
  group_by(SP)%>%
  summarise(range(na.omit(RMR)),sd(na.omit(RMR)),sd(na.omit(Cresp)),range(na.omit(`Normalised δ13C ‰VPDB Mean`)))

#Oto = subset(Oto, SP =="Trout"&Cresp<0.2)

#Cresp
ggplot(Oto, aes(x=Cresp, y=(MR),color=SP))+geom_point()+geom_smooth(method="lm")
ggplot(Oto, aes(x=Cresp, y=(SMR2),color=SP))+geom_point()+geom_smooth(method="lm")
ggplot(Oto, aes(x=Cresp, y=(RMR),color=SP))+geom_point()+geom_smooth(method="lm")
ggplot(Oto, aes(x=Cresp, y=(MMR),color=SP))+geom_point()+geom_smooth(method="lm")

m1=lm(Cresp~MR3, data=Oto)
m1=lm(Cresp~SMR3, data=Oto)
m1=lm(Cresp~RMR3, data=Oto)
m1=lm(Cresp~MMR3, data=Oto)
summary(m1)

#FMR
ggplot(Oto, aes(x=FMR, y=MR3,color=SP))+geom_point()+geom_smooth(method="lm")
ggplot(Oto, aes(x=FMR, y=SMR3,color=SP))+geom_point()+geom_smooth(method="lm")
ggplot(Oto, aes(x=FMR, y=RMR3,color=SP))+geom_point()+geom_smooth(method="lm")
ggplot(Oto, aes(x=FMR, y=MMR3,color=SP))+geom_point()+geom_smooth(method="lm")

#Chem temp
Oto=mutate(Oto, Temp = )
Oto=mutate(Oto, Temp2 = (`Normalised δ18O ‰VPDB Mean`-(-7)-3.72)/-0.19)


#Now look at centered values
Oto2=Oto%>%
  group_by(SP)%>%
  mutate(across(c(SMR3,RMR3,MMR3,MR3, FMR,Cresp),
                ~ .x - median(.x, na.rm = TRUE),
                .names = "{.col}_2"))
median(Oto2$FMR)
#subset
#Oto2 = subset(Oto2, SP =="Trout")
#Oto2 = subset(Oto2, FMR<0.2)

#Plot
p1=ggplot(Oto2, aes(x=FMR_2, y=MR3_2,color=SP))+geom_point()+geom_smooth(method="lm")+ylab(expression(paste(RMR[F])))+xlab("FMR")+theme_bw()+Theme
p2=ggplot(Oto2, aes(x=FMR_2, y=SMR3_2,color=SP))+geom_point()+geom_smooth(method="lm")+ylab("SMR")+xlab("FMR")+theme_bw()+Theme
p3=ggplot(Oto2, aes(x=FMR_2, y=RMR3_2,color=SP))+geom_point()+geom_smooth(method="lm")+ylab(expression(paste(RMR[L])))+xlab("FMR")+theme_bw()+Theme
p4=ggplot(Oto2, aes(x=FMR_2, y=MMR3_2,color=SP))+geom_point()+geom_smooth(method="lm")+ylab("MMR")+xlab("FMR")+theme_bw()+Theme

library(cowplot)
p = plot_grid(p1,p2,p3,p4, ncol = 2,align = "v", labels = c("a","b","c","d"))
p

#Plot mass
ggplot(Oto2, aes(x=Weight, y=FMR_2))+geom_point()+geom_smooth(method="lm")+facet_wrap(~SP,scales="free")+theme_bw()+Theme



# Poster ------------------------------------------------------------------
# Poster ------------------------------------------------------------------
Data$Species=Data$SP
library(svglite)
install.packages("systemfonts")
Theme = theme(panel.grid.major = element_blank(),panel.grid.minor = element_blank(),axis.title=element_text(size=24),axis.text=element_text(size=22))

#Plot 1
ggplot(Data,aes(y=log(SMR3), x=log(MR3),color=Species))+geom_point(size=3)+geom_smooth(method="lm",size=2.5)+theme_bw()+Theme+
  ylab(expression(paste("logSMR (mg O"[2]," g"^-"0.91"," h"^-1,")")))+
  scale_color_manual(values = c("#40B0A6", "#CC6677", "#E1BE6A", "#F0E442", "#0072B2", "#D55E00", "#CC79A7"))+
  xlab(expression(paste("log", RMR[F], " (mg O"[2]," g"^-"0.76"," h"^-1,")")))+theme(legend.position="none")

ggsave("C:/Users/peter/OneDrive/Life/Marine Biology/PhD Metabolic Drivers of Growth and Survival in Salmonids/Chapters/Papers/Chapter 1 Method Validation/Data/Field vs Lab Respirometry/Plots/Poster1.eps", width = 9, height = 6.5, units = "in", dpi = 300)





Oto3 = select(Oto, ID,FMR)

Data2=merge(Data,Oto3, by=c("ID"),all = TRUE)


#Plot2
#prep Data
Long =  dplyr::select(Data2, ID,Day,SP, SMR3,RMR3,MR3,MMR3,Weight,FMR)
library(data.table)
long <- melt(setDT(Long), id.vars = c("ID","SP","Day","Weight"), variable.name = "Method")
long=na.omit(long)

#Relabel
long$Method <- factor(long$Method, levels = c("SMR3", "RMR3", "MR3", "MMR3","FMR"),
                      labels = c("SMR", "RMR^L", "RMR^F", "MMR","FMR"))

long = long%>%
  mutate(SP = recode(SP, "Trout" = "Brown Trout"))%>%
  mutate(SP = recode(SP, "Minnow" = "European Minnow"))%>%
  mutate(SP = recode(SP, "Stickleback" = "Three Spined Stickleback"))
desired_order <- c("European Minnow", "Three Spined Stickleback", "Brown Trout")
long$SP <- factor(long$SP, levels = desired_order)


#V2
ggplot(long, aes(x = Method, y = log(value),color=SP)) +
  geom_boxplot(outlier.shape = NA) +
  geom_jitter(width = 0.05, size = 1.5,color="black") +
  facet_wrap(~SP, scales = "free_x",drop=TRUE) +  # THIS is key
  theme_bw() + Theme+
  scale_color_manual(values = c("#40B0A6", "#CC6677", "#E1BE6A", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")) +
  theme(
    legend.position = "none",
    strip.text = element_text(size = 20)
  ) +
  ylab(expression(paste("log Metabolic Rate (mg O"[2]," g"^-"b"," h"^-1,")"))) +
  scale_x_discrete(
    labels = c(
      "SMR" = "SMR",
      "RMR^L" = bquote(RMR[L]),
      "RMR^F" = bquote(RMR[F]),
      "FMR" = "FMR",
      "MMR" = "MMR"
    )
  )


ggsave("Plots/Poster2.eps", width = 20, height = 7, units = "in", dpi = 300)









str(Oto)
Oto2=subset(Oto,`Normalised δ18O ‰VPDB Mean`< -5.62 )
####Checking Oto d13C vs d18O
ggplot(Oto2, aes(x=`Normalised δ18O ‰VPDB Mean`,y=`Normalised δ13C ‰VPDB Mean`))+geom_point()+geom_smooth(method="lm")
#I belive that this shows me that otoliths with a lower d13C e.g. that have more non lab material (we believe lab is -8 ish) 
#have a higher d18O which means colder temperature this would make sense if the field is colder than the lab as we would expect
#But the lab was chosen to be a similar temp to the field.


ggplot(Oto, aes(x=`Normalised δ13C ‰VPDB Mean`,y=Weight))+geom_point()+geom_smooth(method="lm")
ggplot(Oto, aes(x=`Normalised δ18O ‰VPDB Mean`,y=Weight))+geom_point()+geom_smooth(method="lm")

m1=lm(`Normalised δ18O ‰VPDB Mean`~Weight, Oto)
summary(m1)

m1=lm(`Normalised δ13C ‰VPDB Mean`~`Normalised δ18O ‰VPDB Mean`, Oto2)
summary(m1)
